<script setup lang="ts">
import Modal from './Modal.vue';
import { ref, useTemplateRef, onMounted } from 'vue';
import { MessageBox } from './MessageBox';

const modal_alert_ref = useTemplateRef<InstanceType<typeof Modal>>('modal_alert');
const modal_confirm_ref = useTemplateRef<InstanceType<typeof Modal>>('modal_confirm');
let callbacks: {cancle: (() => void) | null, submit: (() => void) | null, close: (() => void) | null} = {cancle: null, submit: null, close: null};
let alert_title = ref("提示");
let alert_msg = ref("");
let confirm_title = ref("提示");
let confirm_msg = ref("");

onMounted(() => {
    MessageBox.alert_fn = alert;
    MessageBox.confirm_fn = confirm; 

})

function set_callback(cb_submit: (() => void) | null,cb_cancle: (() => void) | null,  cb_close: (() => void) | null){
    callbacks.cancle = cb_cancle;
    callbacks.submit = cb_submit;
    callbacks.close = cb_close;
}
function clear_callback(){
    callbacks.cancle = null;
    callbacks.submit = null;
    callbacks.close = null;
}
function alert(title: string='提示', msg: string='') {
    alert_title.value = title;
    alert_msg.value = msg;
    modal_alert_ref.value?.open();
}
function confirm(title: string='提示', msg: string='', cb_submit: (() => void) | null,cb_cancle: (() => void) | null,  cb_close: (() => void) | null) {
    set_callback(cb_submit,cb_cancle,cb_close);
    confirm_title.value = title;
    confirm_msg.value = msg;
    modal_confirm_ref.value?.open();
}
function on_modal_confirm_cancel() {
    modal_confirm_ref.value?.close();
    
    if (callbacks.cancle) {
        callbacks.cancle(); 
    }
    clear_callback();
}
function on_modal_confirm_submit() {
    modal_confirm_ref.value?.close();
    
    if (callbacks.submit) {
        callbacks.submit(); 
    }
    clear_callback();
}
function on_modal_confirm_close() { 
    modal_confirm_ref.value?.close();
    
    if (callbacks.close) {
        callbacks.close(); 
    }  
    clear_callback();
}
function on_modal_alert_close() {
    modal_alert_ref.value?.close();
}
function on_modal_alert_submit() {
    modal_alert_ref.value?.close();
}

defineExpose({
    alert, confirm
})
</script>

<template>
<Modal ref="modal_alert" :title="alert_title" :msg="alert_msg" @submit="on_modal_alert_submit" @close="on_modal_alert_close">
    <template #footer="footer">
        <button @click="footer.cb_submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">{{ footer.submit_label }}</button>
    </template>

</Modal>
<Modal ref="modal_confirm" :title="confirm_title" :msg="confirm_msg" @cancel="on_modal_confirm_cancel" @submit="on_modal_confirm_submit" @close="on_modal_confirm_close"></Modal>
</template>

<style scoped>

</style>